# 用于访问标准输入输出
import sys
import json


class MCPServer:
    def __init__(self):
        # 定义服务器支持的工具列表
        self.tools = {
            # 工具1 读取文件
            "read_file": {
                "description": "读取指定文件的内容",
                "parameters": {
                    "type": "object",
                    "properties": {
                        "file_path": {
                            "type": "string",
                            "description": "要读取的文件的路径",
                        }
                    },
                    "required": ["file_path"],
                },
            },
            # 工具2 获取指定城市的天气预报
            "get_weather": {
                "description": "获取指定城市的天气信息",
                "parameters": {
                    "type": "object",
                    "properties": {
                        "city": {
                            "type": "string",
                            "description": "城市的名称",
                        }
                    },
                    "required": ["city"],
                },
            },
        }

    def _read_file(self, args, request_id):
        file_path = args.get("file_path")
        try:
            with open(file_path, "r", encoding="utf-8") as f:
                content = f.read()
            return {
                "jsonrpc": "2.0",
                "id": request_id,
                "result": {
                    "content": [
                        {"type": "text", "text": f"文件{file_path}内容为{content}"}
                    ]
                },
            }
        except Exception as e:
            return {
                "jsonrpc": "2.0",
                "id": request_id,
                "error": {"code": -32000, "message": f"读取文件失败:{str(e)}"},
            }

    def handle_request(self, request):
        # 获取请求的方法
        method = request.get("method")
        # 获取请求的参数
        params = request.get("params", {})
        if method == "tools/list":
            return {
                "jsonrpc": "2.0",
                "result": {"tools": list(self.tools.values())},
                "id": request["id"],
            }
        elif method == "tools/call":
            tool_name = params.get("name")
            tool_args = params.get("arguments")
            if tool_name == "read_file":
                return self._read_file(tool_args, request.get("id"))
            else:
                return {
                    "jsonrpc": "2.0",
                    "id": request.get("id"),
                    "error": {"code": -32601, "message": f"Method {method} not found"},
                }
        else:
            return {
                "jsonrpc": "2.0",
                "id": request.get("id"),
                "error": {"code": -32601, "message": f"Method {method} not found"},
            }


if __name__ == "__main__":
    mcpServer = MCPServer()
    # 从标准输入循环读取每一行数据
    for line in sys.stdin:
        try:
            # 解析JSON请求
            request = json.loads(line.strip())
            # 处理客户端请求，返回服务器响应
            response = mcpServer.handle_request(request)
            # 输出响应到标准输出
            # print(json.dumps(response, ensure_ascii=False))
            # 在标准输出里写入的时候必须输入换行符才意味本次输入结束
            sys.stdout.write(json.dumps(response, ensure_ascii=False) + "\n")
            # 刷新标准输出缓冲区
            sys.stdout.flush()
        except json.JSONDecodeError:
            # 向标准输出错误响应数据
            print(
                json.dumps(
                    {
                        "jsonrpc": "2.0",
                        "id": None,
                        "error": {
                            "code": -32700,
                            "message": "解析错误（Invalid JSON）",
                        },
                    },
                    ensure_ascii=False,
                )
            )
            # 刷新标准输出缓存区
            sys.stdout.flush()
